package com.atcc.test.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.aliyuncs.utils.StringUtils;
import com.atcc.test.service.SmsService;

@RestController
@RequestMapping("/")
@CrossOrigin
public class SmsController {
	
	@Autowired
	private SmsService smsService;
	
	@Autowired
	private RedisTemplate<String,String> redisTemplate;
	
	@GetMapping("sendMessage/{phoneNumber}")
	public String SendMessage(@PathVariable("phoneNumber") String phoneNumber) {
		String code = redisTemplate.opsForValue().get(phoneNumber);
		if(!StringUtils.isEmpty(code)) {
			return "用户号码："+phoneNumber+" 验证码： " + code + "未过期";
		}
		code = UUID.randomUUID().toString().substring(0,4);
		Map<String, Object> param = new HashMap<>();
		param.put("code", code);
		boolean isSendSuccess = smsService.SendMessage(phoneNumber, param);
		
		if(isSendSuccess) {
			redisTemplate.opsForValue().set(phoneNumber, code,60,TimeUnit.SECONDS);
			return "用户号码："+phoneNumber+" 验证码： " + code + "发送成功"; 
		}else {
			return "用户号码："+phoneNumber+" 验证码： " + code + "未过期";
		}
	}

}
